package com.bobi.tfca.ui.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bobi.tfca.R
import com.bobi.tfca.databinding.ItemShowArticleParagraphBinding
import com.bobi.tfca.network.response.ParagraphResponse
import com.bobi.tfca.ui.article.ShowArticleFragment
import com.bobi.tfca.util.LogUtil
import com.bumptech.glide.Glide
import java.util.ArrayList

class ShowParagraphAdapter(
    val fragment: ShowArticleFragment,
    var paragraphList: ArrayList<ParagraphResponse>
) :
    RecyclerView.Adapter<ShowParagraphAdapter.ParagraphViewHolder>() {

    inner class ParagraphViewHolder(private val binding: ItemShowArticleParagraphBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(paragraph: ParagraphResponse) {
            // 加载图片
            val url = paragraph.picture
            if (url.isNotBlank() && (!"null".equals(url))) {
                Glide.with(fragment).load(url).placeholder(R.drawable.defaultbg_h)
                    .into(binding.ivPicture)
            } else {
                binding.ivPicture.visibility = View.GONE
            }
            if (paragraph.plainText.isNotBlank()) {
                binding.tvPlainText.text = paragraph.plainText
            } else {
                binding.tvPlainText.text = ""
            }
        }
    }

    fun setItemList(list: ArrayList<ParagraphResponse>) {
        this.paragraphList = list
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ParagraphViewHolder {
        val itemView = ItemShowArticleParagraphBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        val viewHolder = ParagraphViewHolder(itemView)
        return viewHolder
    }

    override fun getItemCount(): Int = paragraphList.size

    override fun onBindViewHolder(holder: ParagraphViewHolder, position: Int) {
        val paragraph = paragraphList[position]
        with(holder) {
            bind(paragraph)
        }
    }
}